import {AbstractReducerGroup} from '../storeBase';
import {SET_TOKEN} from './actions';
import {storageGet, storageSet} from '../storage';

export const TOKEN_NAME = 's_token';

class TokenReducer extends AbstractReducerGroup {
    state = {
        tokenStr: storageGet(TOKEN_NAME),
        user: null,
    };
    handlers = {};

    constructor() {
        super();
        const _this = this;
        this.handlers[SET_TOKEN] = action => {
            const {user, token} = action;
            storageSet(TOKEN_NAME, token);
            _this.state = {
                ...this.state,
                tokenStr: token,
                user: user,
            };
        };
    }

    getState() {
        return this.state;
    }

    handleAction(type, action) {
        if (type in this.handlers) {
            this.handlers[type](action);
        }
        return this.state;
    }

    getName() {
        return 'token';
    }
}

export default TokenReducer;